import datetime
import ConfigParser
import sys
from kit import kit
from decimal import Decimal

def find_next_change(index,arr):
	while True:
		if index < len(arr)-1:
			index=index+1
			if arr[index][2]!=arr[index-1][2]:
				return index
		else:
			break
	return index

def date2str(date):
	return datetime.datetime.strftime(date,'%Y.%m.%d %H:%M')

def is_peak(nr1,nr2):
	peak=0.01
	if (int(nr1[2]*100)-int(nr2[2]*100)-int(peak*100))==0:
		return True
	else:
		return False
def formatfloat(value, decimals = 2, sep = ","):
	return "%s%s%d" % (int(value), sep, abs(int(value*100-int(value)*100)))

def app_factor(arr,pip):
	i=0
	first=arr[0][2]
	min=first
	while True:
		if i < len(arr)-10:
			next=find_next_change(i,arr)
			if abs(arr[next][2]-arr[i][2]) < min:
				min=abs(arr[next][2]-arr[i][2])
		else:
			break
		i=next
	return (first+min)*(1-pip)-first*(1+pip)


if __name__ == "__main__":
	try:
		cp= ConfigParser.RawConfigParser( )
		cp.read( r"hissedb.cfg" )
		sql_server=cp.get('SQL','server')
		sql_port=int(cp.get('SQL','port'))
		sql_username=cp.get('SQL','username')
		sql_password=cp.get('SQL','password')
		sql_database=cp.get('SQL','database')
		kagitlar=cp.get('SNIFFER','hisseler')
		kagitlar=kagitlar.split(',')
		url=cp.get('SNIFFER','url')
	except Exception,e:
		print e
		print 'No acceptable config file found'
		sys.exit()
	single=False
	toolkit=kit()
	if len(sys.argv)>1:
		stock=sys.argv[1]
		print "Manual stock :" + stock 
		kagitlar=[stock]
		single=True
	browser=toolkit.create_browser()
	db=toolkit.connect_db(sql_server,sql_port,sql_username,sql_password,sql_database)
	cursor=db.cursor()
	if not single: print "HISSE;SUCCESS;SUCCESSFUL TR;FAILURE;FAILURE TR;CUMULATIVE;APP. FACT."
	for kagit in kagitlar:
		cursor.execute("""select hisse,date,al from degerler where hisse=%s and date>%s and date<%s order by date""", (kagit,"2012-03-15","2012-03-16"))
		values=cursor.fetchall()
		pros=0
		cons=0
		tr_pros=0
		tr_cons=0
		index=0
		i=0
		capital=100
		pip=0.004
		if len(values) > 0 :
			af=app_factor(values,pip)
		else:
			break
		if af > 0 :
			while True:
				index=i
				if index >= len(values)-1:
					break
				p1=values[index]
				index=find_next_change(index,values)
				nexti=index
				p2=values[index]
				index=find_next_change(index,values)
				p3=values[index]
				index=find_next_change(index,values)
				p4=values[index]
				index=find_next_change(index,values)
				current=values[index]
				index=find_next_change(index,values)
				next=values[index]
		#		print date2str(current[1]) + " ; " + str(current[2])
				if p2[2] > p1[2] and p2[2] > p3[2] and p3[2] < p4[2] and p4[2] > current[2]:
					if single : print "P1: " + date2str(p1[1])  + " - " + str(p1[2])
					if single : print "P2: " + date2str(p2[1])  + " - " + str(p2[2])
					if single : print "P3: " + date2str(p3[1])  + " - " + str(p3[2])
					if single : print "P4: " + date2str(p4[1])  + " - " + str(p4[2])
					if single : print "Current: " + date2str(current[1])  + " - " + str(current[2])
					if single : print "Next: " + date2str(next[1])  + " - " + str(next[2])
					current_act=current[2]+current[2]*pip
					next_act=next[2]-next[2]*pip
					rate=(next_act-current_act)/current_act
					capital+=capital*rate
					if current_act < next_act:
						if single : print "SUCCESS: "+ str(rate*100)+ "\n"
						pros+=(next_act-current_act)/current_act*100
						tr_pros+=1

					else:
						if single : print "FAILURE: "+ str(rate*100)+ "\n"
						cons+=(current_act-next_act)/current_act*100
						tr_cons+=1
				i=nexti
			if single: print "HISSE;SUCCESS;SUCCESSFUL TR;FAILURE;FAILURE TR;CUMULATIVE; APP. FACT."
			print kagit + ";" + formatfloat(pros) +";"+ str(tr_pros)+ ";" + formatfloat(cons) + ";"+ str(tr_cons)+";" + formatfloat(capital-100)+";"+str(af).replace('.',',')
		else :
			print kagit +";0;0;0;0;0;"+ str(af).replace('.',',')